package com.atguigu.gmall.common.config.minio.service.impl;

import com.atguigu.gmall.common.config.minio.MinioProperties;
import com.atguigu.gmall.common.config.minio.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author:ahang
 * @create:2022-09-28 22:31
 * @Description:
 */
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    MinioProperties minioProperties;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        //防止文件名相同被覆盖问题
        String name = UUID.randomUUID().toString().replaceAll("-","")+ "_"+file.getOriginalFilename();
        InputStream fileInputStream = file.getInputStream();
        //1.创建客户端
        //2.判断桶是否存在

        //3.使用putObject上传文件
        PutObjectOptions putObjectOptions = new PutObjectOptions(file.getSize(),-1);
        minioClient.putObject(minioProperties.getBucketName(),name,fileInputStream,putObjectOptions);

        //返回文件的访问路径
        String url = minioProperties.getEndpoint()+"/"+ minioProperties.getBucketName() +"/"+name;
        return url;
    }
}
